package cn.imvc.app.models;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.util.BeanUtil;

import cn.imvc.app.domains.FundFlowType;
import cn.imvc.app.entities.Account;
import cn.imvc.app.entities.Withdrawals;
import cn.imvc.app.repositories.WithdrawalsRepository;
import cn.imvc.data.domain.ViewRequest;
@Service
public class WithdrawalsModelImpl implements WithdrawalsModel {
	@Autowired
	private WithdrawalsRepository withdrawalsRepository;
	@Autowired
	private FundFlowModel fundFlowModel;
	@Autowired
	private AccountModel accountModel;
	public Page<Withdrawals> findAll(ViewRequest viewRequest) {
		if(viewRequest == null){
			viewRequest = new ViewRequest();
		}
		viewRequest.getSort().put("createdAt", "DESC");
		return withdrawalsRepository.findAll("distinct w","Withdrawals w left join w.member m",viewRequest);
	}
	public void updateWithdrawalsSuccess(int id,Withdrawals withdrawals) {
		Withdrawals oldWithdrawals = withdrawalsRepository.findOne(id);
		if(oldWithdrawals.getState() == 10){
			oldWithdrawals.setPayCode(withdrawals.getPayCode());
		}
		oldWithdrawals.setState((byte) 11);
		oldWithdrawals.setUpdatedAt(new Date());
		oldWithdrawals.setWithdrawalsTime(new Date());
		oldWithdrawals.setReply(withdrawals.getReply());
		withdrawalsRepository.saveAndFlush(oldWithdrawals);
		
	}
	public void updateWithdrawalsFail(int id,Withdrawals withdrawals) {
		Withdrawals oldWithdrawals = withdrawalsRepository.findOne(id);
		oldWithdrawals.setState((byte) 12);
		oldWithdrawals.setUpdatedAt(new Date());
		oldWithdrawals.setReply(withdrawals.getReply());
		withdrawalsRepository.saveAndFlush(oldWithdrawals);
		
		fundFlowModel.saveFundFlow(oldWithdrawals.getMember(), oldWithdrawals.getMoney(), oldWithdrawals.getCode(), FundFlowType.WithdrawalsFailed.getValue());
		
		accountModel.retrySaveAccount(oldWithdrawals.getMember().getAccount().getId(), oldWithdrawals.getMoney(), 0, 0);
	}
	public Withdrawals getOne(int id) {
		return withdrawalsRepository.getOne(id);
	}
	public Page<Withdrawals> findAllByMemberId(ViewRequest viewRequest, int id) {
		if(viewRequest == null){
			viewRequest = new ViewRequest();
		}
		viewRequest.getSort().put("createdAt", "DESC");
		viewRequest.getParams().put("_and_w_dot_member_dot_id_eq_number",id+"");
		return withdrawalsRepository.findAll("w","Withdrawals w",viewRequest);
	}
}
